//
//  Snake.cpp
//  Snake
//
//  Created by CmST0us on 16/11/25.
//  Copyright © 2016年 SpringEngine. All rights reserved.
//

#include "Snake.hpp"
#include <ncurses.h>
#include "Food.hpp"
#include "Frame.hpp"
Snake::Snake(){
    this->_direction.x = 1;
    this->_direction.y = 0;
    Point headPoint = {
        .x = 20,
        .y = 40
    };
    
    this->_body = new Body(headPoint, Body::headShape);
    headPoint.x--;
    _body->addBody(headPoint, Body::bodyTail);
}

void Snake::bodyToHead(){
    BodyRef pNode = this->_body;
    for (; ; ) {
        if (pNode->front == nullptr) {
            //head!!!
            this->_body = pNode;
            return;
        }else{
            pNode = pNode->front;
        }
    }
}
Snake::MOVE_STATE Snake::move(FoodRef food, const Frame& frame){
    Point addPoint;
    addPoint.x = this->_body->point.x + this->_direction.x;
    addPoint.y = this->_body->point.y + this->_direction.y;
    
    if (food->point == addPoint) {
        //ear food
        this->_body->addBody(addPoint, Body::bodyHead);
        this->bodyToHead();
        return STATE_FOOD;
    }else if(
             addPoint.x <= frame.orig.x ||  //左边的墙
             addPoint.y >= frame.size.y ||  //下面的墙
             addPoint.x >= frame.size.x ||  //右边的墙
             addPoint.y <= frame.orig.y
             ) return STATE_WALL;
    else if (this->_body->searchBody(addPoint) != nullptr) return STATE_SELFKILL;
    else{
        this->_body->addBody(addPoint, Body::bodyHead);
        this->bodyToHead();
        this->_body->delBody(Body::bodyTail);
        return STATE_NORMAL;
    }
    
    return STATE_SELFKILL;
//    printf("Head At Point: [\t%d\t%d\t]", this->_body->point.x, this->_body->point.y);
}